package com.czl.module_storehouse.activity.inventory.add;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.czl.base.data.bean.tengyun.CategoryBean;
import com.czl.module_base.activity.BaseActivity;
import com.czl.module_base.bean.CompanyBean;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.mvp.view.SimpleView;
import com.czl.module_base.utils.PopWindowUtils;
import com.czl.module_storehouse.R;
import com.czl.module_base.adapter.CategoryAdapter;
import com.czl.module_base.adapter.ListTree;
import com.czl.module_base.adapter.ListTreeAdapter;
import com.czl.module_storehouse.bean.InventoryInfoBean;
import com.czl.module_storehouse.databinding.ActivityInventoryAddBinding;
import com.czl.module_storehouse.event.InventoryAddEvent;
import com.czl.module_storehouse.mvp.presenter.CategoryPresenter;
import com.czl.module_storehouse.mvp.presenter.CompanyPresenter;
import com.czl.module_storehouse.mvp.presenter.InventoryPresenter;
import com.czl.module_storehouse.mvp.view.InventoryView;
import com.czl.module_storehouse.widget.flowlayout.FlowLayout;
import com.czl.module_storehouse.widget.flowlayout.TagAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 添加盘点单
 *
 * @author xubin
 */
public class InventoryAddActivity extends BaseActivity<ActivityInventoryAddBinding> implements InventoryView, SimpleView {

    private List<CompanyBean> mCompanyBeanList;
    private List<CategoryBean> mCategoryBeanList;
    private final InventoryInfoBean mInventoryInfoBean = new InventoryInfoBean();
    private final List<CategoryBean> mSelectCategorys = new ArrayList<>();
    private TagAdapter<CategoryBean> mAdapter;
    private final List<CategoryBean> mTags = new ArrayList<>();

    @InjectPresenter
    CompanyPresenter mCompanyPresenter;

    @InjectPresenter
    InventoryPresenter mInventoryPresenter;

    @InjectPresenter
    CategoryPresenter mCategoryPresenter;

    @Override
    protected ActivityInventoryAddBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityInventoryAddBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mToolBinding.toolbarContentTitle.setText("盘点单");
        binding.tvInvCompany.setOnClickListener(v -> selectCompanyList1());
        binding.tvInvSort.setOnClickListener(v -> getClassificationListCompany());
        binding.tvOutsize.setOnClickListener(v -> showPopupRange());
        binding.textAdd.setOnClickListener(v -> submit());
        setTagAdapter();
    }

    private void setTagAdapter() {
        mAdapter = new TagAdapter<CategoryBean>(mTags) {
            @Override
            public View getView(FlowLayout parent, int position, CategoryBean tag) {
                View view = View.inflate(getContext(), R.layout.layout_tag_class, null);
                TextView tvName = view.findViewById(R.id.tv_name);
                tvName.setText(tag.getName());

                tvName.setOnLongClickListener(v -> {
                    mTags.remove(tag);
                    mAdapter.notifyDataChanged();
                    mSelectCategorys.remove(tag);
                    List<CategoryBean> children = tag.getChildren();
                    if (children != null) {
                        mSelectCategorys.removeAll(children);
                        for (CategoryBean categoryBean : children) {
                            List<CategoryBean> children1 = categoryBean.getChildren();
                            if (children1 != null) {
                                mSelectCategorys.removeAll(children1);
                            }
                        }
                    }
                    resetClass();
                    return false;
                });
                return view;
            }
        };
        binding.flowLayout.setAdapter(mAdapter);
    }

    private void resetClass() {
        if (mAdapter.getCount() == 0) {
            binding.tvInvSort.setText("全部");
            mSelectCategorys.clear();
        } else {
            binding.tvInvSort.setText("请选择分类");
        }
    }

    private void selectCompanyList1() {
        if (mCompanyBeanList == null) {
            if (mCompanyPresenter != null) {
                mCompanyPresenter.selectCompanyList();
            }
        } else {
            showCompanyPopup();
        }
    }

    private void showCompanyPopup() {
        List<String> list = new ArrayList<>();
        if (mCompanyBeanList != null) {
            for (CompanyBean bean : mCompanyBeanList) {
                String companyName = bean.getCompanyName();
                if (TextUtils.isEmpty(companyName)) {
                    continue;
                }
                list.add(companyName);
            }
        }
        showRecyclerViewPopupWindow(list, "选择公司", (adapter, view, position) -> {
            resetData();
            CompanyBean bean = mCompanyBeanList.get(position);
            mInventoryInfoBean.setPropCompanyId(bean.getCompanyId());
            mInventoryInfoBean.setPropCompanyName(bean.getCompanyName());
            mInventoryInfoBean.setPropCompanyShortName(bean.getCompanyShortName());
            binding.tvInvCompany.setText(list.get(position));
        });
    }

    private void getClassificationListCompany() {
        String propCompanyId = mInventoryInfoBean.getPropCompanyId();
        if (TextUtils.isEmpty(propCompanyId) || "0".equals(propCompanyId)) {
            showToast("请选择产权公司");
            return;
        }
        int inventoryRange = mInventoryInfoBean.getInventoryRangeInt();
        if (mInventoryPresenter != null) {
            List<Integer> list = new ArrayList<>();
            if (inventoryRange == 0) {
                list.add(1);
                list.add(2);
            } else if (inventoryRange == 1) {
                //低耗品
                list.add(1);
            } else {
                //固定资产
                list.add(2);
            }
            mCategoryPresenter.getclassificationlistCompany(propCompanyId, list);
        }
    }

    private void showPopupRange() {
        String[] strings = getResources().getStringArray(R.array.select_inventory_items);
        List<String> list = Arrays.asList(strings);
        showRecyclerViewPopupWindow(list, "选择盘点范围", (adapter, view, position) -> {
            //选择盘点范围
            if (position == 0) {
                mInventoryInfoBean.setInventoryRange(null);
            } else if (position == 1) {
                mInventoryInfoBean.setInventoryRange(2);
            } else if (position == 2) {
                mInventoryInfoBean.setInventoryRange(1);
            }
            resetDataClass(position);
            binding.tvOutsize.setText(list.get(position));
        });
    }

    private void resetData() {
        mInventoryInfoBean.setInventoryRange(null);
        binding.tvOutsize.setText("全部");
        binding.tvInvSort.setText("全部");
        mTags.clear();
        mAdapter.notifyDataChanged();
        mSelectCategorys.clear();
    }

    private void resetDataClass(int position) {
        if (position > 0) {
            binding.tvInvSort.setText("请选择分类");
        } else {
            binding.tvInvSort.setText("全部");
        }
        mTags.clear();
        mAdapter.notifyDataChanged();
        mSelectCategorys.clear();
    }

    private void showSortPopup() {
        if (mCategoryBeanList == null || mCategoryBeanList.size() == 0) {
            showToast("没有数据");
            return;
        }
        ListTree listTree = new ListTree();
        View view = View.inflate(getContext(), R.layout.common_recycler_view, null);
        RecyclerView recyclerView = view.findViewById(R.id.rv_item);
        CategoryAdapter categoryAdapter = new CategoryAdapter(listTree);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(categoryAdapter);
        categoryAdapter.addAll(mCategoryBeanList);
        int itemCount = categoryAdapter.getItemCount();
        int width = ScreenUtils.getScreenWidth() - SizeUtils.dp2px(30);
        if (itemCount > 8) {
            int height = (int) (ScreenUtils.getScreenHeight() * 0.6f);
            PopWindowUtils.getInstance().createPopWindow(getContext(), view, width, height, "选择分类");
        } else {
            PopWindowUtils.getInstance().createPopWindow(getContext(), view, width, "选择分类");
        }
        PopWindowUtils.getInstance().showBasePopupWindow(binding.getRoot());
        categoryAdapter.setOnItemClickListener((ListTreeAdapter.OnItemClickListener<CategoryBean>) (categoryBean, title, pIdPath) -> {
            PopWindowUtils.getInstance().dismissPopupWindow();
            if (isAdd(mSelectCategorys, categoryBean)) {
                //数据已添加
                showToast("分类已添加");
            } else {
                mSelectCategorys.add(categoryBean);
                addCategoryList(categoryBean);
                addClass(categoryBean);
            }
        });
    }

    private void addCategoryList(CategoryBean categoryBean) {
        if (categoryBean != null) {
            mSelectCategorys.add(categoryBean);
            List<CategoryBean> children = categoryBean.getChildren();
            if (children == null) {
                return;
            }
            for (CategoryBean child : children) {
                addCategoryList(child);
            }
        }
    }

    public boolean isAdd(List<CategoryBean> list, CategoryBean categoryBean) {
        if (list == null || list.isEmpty() || categoryBean.getId() == null) {
            return false;
        }
        for (CategoryBean bean : list) {
            if (categoryBean.getId().equals(bean.getId())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 添加分类
     *
     * @param bean
     */
    private void addClass(CategoryBean bean) {
        binding.tvInvSort.setText("请选择分类");
        mTags.add(bean);
        mAdapter.notifyDataChanged();
    }

    private void submit() {
        String name = binding.etName.getText().toString();
        if (TextUtils.isEmpty(name)) {
            showToast("填写盘点名称");
            return;
        }
        String propCompanyId = mInventoryInfoBean.getPropCompanyId();
        if (TextUtils.isEmpty(propCompanyId)) {
            showToast("请选择产权公司");
            return;
        }
        mInventoryInfoBean.setInventoryName(name);
        String desc = binding.etInvDesc.getText().toString();
//        if (TextUtils.isEmpty(desc)) {
//            showToast("填写盘点说明");
//            return;
//        }
        mInventoryInfoBean.setInventoryComment(desc);
        Set<Integer> list = new HashSet<>();
        for (CategoryBean bean : mSelectCategorys) {
            list.add(bean.getId());
        }
        mInventoryInfoBean.setInventoryClass(new ArrayList<>(list));
        if (mInventoryPresenter != null) {
            mInventoryPresenter.addInventoryInfo(mInventoryInfoBean);
        }
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (CompanyPresenter.TAG_COMPANY_LIST.equals(httpResponse.getRequestTag())) {
            mCompanyBeanList = (List<CompanyBean>) httpResponse.getData();
            showCompanyPopup();
        } else if (CategoryPresenter.TAG_CATEGORY_LIST.equals(httpResponse.getRequestTag())) {
            //分类
            List<CategoryBean> list = (List<CategoryBean>) httpResponse.getData();
            if (list == null) {
                showToast("没有数据");
                return;
            }
            mCategoryBeanList = list;
            showSortPopup();
        } else if (InventoryPresenter.TAG_INVENTORY_ADD_INFO.equals(httpResponse.getRequestTag())) {
            InventoryAddEvent event = new InventoryAddEvent();
            EventBus.getDefault().postSticky(event);
            //提交成功
            showToast("提交成功");
            finish();
        }
    }
}
